﻿using Furion;
using iemtm.WeChat.Web.Core.Handlers;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Text.Json;
using Microsoft.Extensions.Options;
using Senparc.CO2NET;
using Senparc.Weixin.Entities;
using System;
using Senparc.Weixin.RegisterServices;
using Microsoft.Extensions.Configuration;
using Senparc.Weixin.MP.Sample.CommonService.MessageHandlers.WebSocket;
using Senparc.CO2NET.RegisterServices;
using iemtm.WeChat.Core;
using Serilog;
using iemtm.WeChat.Core.Quartz;
using Quartz;
using Quartz.Impl;
using iemtm.WeChat.Core.RabbitMQ;

namespace iemtm.WeChat.Web.Core
{
    public class Startup : AppStartup
    {
        public IConfiguration Configuration { get; }
        
        public void ConfigureServices(IServiceCollection services)
        {
            #region original
            /*
            services.AddJwt<JwtHandler>();

            services.AddCorsAccessor();

            services.AddControllersWithViews()
                        .AddInjectWithUnifyResult();
            */
            #endregion

            // 注册 JWT 授权
            //services.AddJwt<JwtHandler>();
            //配置JWT+Cookie混合授权
            services.AddJwt<JwtHandler>(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            
            }, enableGlobalAuthorize: true)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, b =>
            {
                b.LoginPath = "/Home/Login";
                b.AccessDeniedPath = "/Home/AccessDenied";
            });

            //远程请求服务
            services.AddRemoteRequest();

            //分布式缓存-暂时用内存缓存代替
            services.AddDistributedMemoryCache();
            //配置跨域
            services.AddCorsAccessor();

            //配置请求审计日志
            services.AddMvcFilter<RequestAuditFilter>();
            //错误日志
            

            //配置MVC
            var Mvc = services.AddControllersWithViews(options =>
            {
                options.EnableEndpointRouting = false;
            }).AddRazorRuntimeCompilation().AddInjectWithUnifyResult().AddAppLocalization().AddJsonOptions(opt => {
                opt.JsonSerializerOptions.PropertyNamingPolicy = null;
            });
            //



            #region 注入 Quartz调度类
            services.AddSingleton<QuartzStartUp>();
            //注册ISchedulerFactory的实例。
            services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
            #endregion


        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime appLifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            //记录请求日志
            app.UseSerilogRequestLogging();
           
            //添加状态码拦截中间件
            app.UseUnifyResultStatusCodes();


            app.UseHttpsRedirection();

            app.UseStaticFiles();
       
            app.UseRouting();

          

            app.UseCorsAccessor();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseInject();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

            #region Quartz任务调度
            //获取前面注入的Quartz调度类         
            var quartz = app.ApplicationServices.GetRequiredService<QuartzStartUp>();
            appLifetime.ApplicationStarted.Register(() =>
            {
                quartz.Start().Wait();
            });


            appLifetime.ApplicationStopped.Register(() =>
            {
                quartz.Stop();
            });
 
 
            #endregion

            MemoryEntity.init();
            RabbitMQHelper.Init();
        }
    }
}